package com.example.warehouse.service.serviceImpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.example.warehouse.entity.Auth;
import com.example.warehouse.mapper.AutoMapper;
import com.example.warehouse.service.AutoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@CacheConfig(cacheNames = "com.example.warehouse.service.serviceImpl.AutoServiceImpl")
@Service
public class AutoServiceImpl implements AutoService {
    @Autowired
    private AutoMapper autoMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public List<Auth> findAuthById(Integer userId) {
        String redis = redisTemplate.opsForValue().get("TreeAuth" + userId);
        if(StringUtils.hasText(redis)){
            List<Auth> reidslist = JSONArray.parseArray(redis, Auth.class);
            return reidslist;
        }
        List<Auth> authById = autoMapper.findAuthById(userId);
        List<Auth> redislist = AllfirstList(authById, 0);
        redisTemplate.opsForValue().set("TreeAuth" + userId, JSON.toJSONString(redislist));
        return redislist;
    }

    public List<Auth> AllfirstList(List<Auth> allAuthlist,Integer pid){

        ArrayList<Auth> firstList=new ArrayList<>();
        for(Auth auth:allAuthlist){
            if(pid.equals(auth.getParentId())){
                firstList.add(auth);
            }
        }

        for(Auth fistAuth:firstList){
            List<Auth> allfirstList = AllfirstList(allAuthlist, fistAuth.getAuthId());
            fistAuth.setChildAuth(allfirstList);
        }
        return firstList;
    }

    @Cacheable(key = "'all:authTree'")
    @Override
    public  List<Auth> allAuthTree(){
        List<Auth> authList=autoMapper.findAllAuth();
        List<Auth> authList1 = AllfirstList(authList, 0);
        return authList1;
    }


}

